package com.sharefacebookexample;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;

import org.json.JSONException;

import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.pm.Signature;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.facebook.Request;
import com.facebook.Response;
import com.facebook.Session;
import com.facebook.SessionState;
import com.facebook.UiLifecycleHelper;
import com.facebook.model.GraphUser;
import com.facebook.widget.FacebookDialog;
/*
 * loginFacebook()
 * logoutFacebook()
 * shareFacebook()
 * setPermission() in order to get infos (mail location)
 * getUserInfos(final Session session)
 * onSessionStateChange() call this method When the state is changed
 * call()
 * onActivityResult very important
 * 
 * 
 * 
 * */
public class MainActivity extends FragmentActivity {

	private static final int FACEBOOK_SHARE_REQUEST_CODE = 1;

	private TextView mTvUsername;
	private Button loginButton;
	private Button shareButton;
	private static final String TAG = "Facebook";
	private UiLifecycleHelper mUiHelper;
	private String mImageUrl = "http://www.epatage-club.ru/wp-content/uploads/2011/09/cat-200x200.jpg";


	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
//		printHashKey();
		mTvUsername = (TextView) findViewById(R.id.tvUsername);
		
		setPermission();
		loginButton = (Button) findViewById(R.id.btnLoginFacebook);
		loginButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				Session ses=Session.getActiveSession();
				if (ses != null) {
					if(ses.isOpened()){
						Log.d("Facebook", "Session will be closed");
						logoutFacebook();
					}
					else if(ses.isClosed()){
						loginFacebook();
						Log.d("Facebook", "Session will be opened");
					}
					else{
						loginFacebook();
						Log.d("Facebook", "Session state unkonwn");
					}
				}
            }
        });
		
		shareButton=(Button)findViewById(R.id.facebook_share);
		shareButton.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				loginFacebook();
				shareFacebook();
			}
		});

		mUiHelper = new UiLifecycleHelper(MainActivity.this, callback);
		mUiHelper.onCreate(savedInstanceState);
	}
	
	@Override
	protected void onResume() {
		super.onResume();
		mUiHelper.onResume();
	}

	@Override
	protected void onPause() {
		super.onPause();
		mUiHelper.onPause();
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		mUiHelper.onDestroy();
	}

	@Override
	protected void onActivityResult(int arg0, int arg1, Intent arg2) {
		// TODO Auto-generated method stub
		super.onActivityResult(arg0, arg1, arg2);
		Log.d("Facebook", "onActivityResult");
		mUiHelper.onActivityResult(arg0, arg1, arg2, new FacebookDialog.Callback() {
			@Override
			public void onError(FacebookDialog.PendingCall pendingCall, Exception error, Bundle data) {
				// Share unsuccessfully.
				Toast.makeText(MainActivity.this, R.string.share_facebook_unsuccessfully, Toast.LENGTH_SHORT)
						.show();
			}

			@Override
			public void onComplete(FacebookDialog.PendingCall pendingCall, Bundle data) {
				// Share successfully.
				Toast.makeText(MainActivity.this, R.string.share_facebook_successfully, Toast.LENGTH_SHORT).show();
				Log.d("Facebook", "activity "+"sucess");
			}
		});
		
	}
	
	private Session.StatusCallback callback = new Session.StatusCallback() {
		@Override
		public void call(Session session, SessionState state,
				Exception exception) {
			Log.d("Facebook", "callback");
			onSessionStateChange(session, state, exception);
		}
	};
	
	private void onSessionStateChange(Session session, SessionState state,
			Exception exception) {
		Log.d("Facebook", "onSessionStateChange");
		if (state.isOpened()) {
			Log.d("Facebook", "Logged in...");
			getUserInfos(session);
		} else if (state.isClosed()) {
			Log.d("Facebook", "Logged out...");
		}
	}
	
	private boolean loginFacebook() {
		Log.d("Facebook", "loginFacebook");
	    if (Session.getActiveSession() == null || !Session.getActiveSession().isOpened()) 
	    {
	    	Session.openActiveSession(this, true, new Session.StatusCallback() {
	            @Override
	            public void call(Session session, SessionState state, Exception exception) 
	            {
	            	onSessionStateChange(session, state, exception);
	            }
	        });
	    	
	        return false;
	    }
	    else
	    {
	    	onSessionStateChange(Session.getActiveSession(), Session.getActiveSession().getState(), null);
	    }
	    return true;
	}
	
	private boolean logoutFacebook(){
		Log.d("Facebook", "logoutFacebook");
		Session sessionOut=Session.getActiveSession();
		if (sessionOut != null) {
			if(sessionOut.isOpened()){
				Log.d("Facebook", "Session opened");
				sessionOut.closeAndClearTokenInformation();
			}
			return true;
		}
		else 
			return false;
	}
	
	void setPermission(){
		Log.d("Facebook", "setPermission");
		List<String> permissions = new ArrayList<String>();
		permissions.add("user_likes");
		permissions.add("email");
		permissions.add("user_location");
		permissions.add("user_birthday");
		
		Session sessionPermission = new Session(this);
		Session.setActiveSession(sessionPermission);
		Session.OpenRequest request = new Session.OpenRequest(this);
		
		request.setPermissions(permissions);
		request.setCallback( callback );
		sessionPermission.openForRead(request);
		
		Session.getActiveSession().close();
	}
	
	
public void getUserInfos(final Session session) {

	Log.d("Facebook", "getUserInfos");
	Request request = Request.newMeRequest(session, 
			new Request.GraphUserCallback() {
		
		@Override
		public void onCompleted(GraphUser user, Response response) {
			// If the response is successful
			if (session == Session.getActiveSession()) {
				if (user != null) {
					Log.i(TAG, "Logged in successfully. User details are below..");
					Log.d("Facebook", "reponse: "+response.toString());
					String firstnameSession=user.getFirstName();
					String lastnameSession=user.getLastName();
					String birthday=user.getBirthday();
					String mailSession=user.getProperty("email").toString();
					String cityStr = null;
					try {
						cityStr = user.getInnerJSONObject().getJSONObject("location").getString("name");
					} catch (JSONException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					Log.d("Facebook", "email"+mailSession+ "city "+cityStr+" firstname "+firstnameSession+
							" lastname "+lastnameSession+" birthday "+birthday);
					mTvUsername.setText(mailSession);
					}
			}
			if (response.getError() != null) {
				Log.i(TAG, "An error is occurred! Message: " + response.getError().getErrorMessage());
			}
		}
	});
	request.executeAsync();
	
}

	/**
	 * Share something to facebook via FacebookDialog.
	 */
	private void shareFacebook() {
		
		Log.d("Facebook", "shareFacebook");
		FacebookDialog shareDialog = new FacebookDialog.ShareDialogBuilder(this)
				.setName("Chat")
				.setApplicationName(getResources().getString(R.string.app_name))
				.setPicture(mImageUrl)
				.setLink("https://www.facebook.com/")
				.setDescription("").setRequestCode(FACEBOOK_SHARE_REQUEST_CODE)
				.build();
		mUiHelper.trackPendingDialogCall(shareDialog.present());
	}

	@Override
	protected void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		mUiHelper.onSaveInstanceState(outState);
	}
	
	public void printHashKey() {

        try {
            PackageInfo info = getPackageManager().getPackageInfo("com.sharefacebookexample",
                    PackageManager.GET_SIGNATURES);
            for (Signature signature : info.signatures) {
                MessageDigest md = MessageDigest.getInstance("SHA");
                md.update(signature.toByteArray());
                Log.d("TEMPTAGHASH KEY:",
                        Base64.encodeToString(md.digest(), Base64.DEFAULT));
            }
        } catch (NameNotFoundException e) {

        } catch (NoSuchAlgorithmException e) {

        }

    }
	

}
